package day01;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class PipedInputOutputStreamDemo01 {
    static PipedInputStream pin = new PipedInputStream();
    static PipedOutputStream pout = new PipedOutputStream();
    public static void main(String[] args) throws IOException {
        pin.connect(pout);
        new Thread(()->{
            try {
                //从文件中读数据
//                BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("D:\\1\\ObjectTest.java")));

                //从键盘获取,然后放到管道中
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入数据");
                String msg = sc.nextLine();
                pout.write(msg.getBytes(StandardCharsets.UTF_8));
//                byte[] buff = new byte[1024];
//                int len = -1;
//                while((len=bin.read(buff))>0) {
//                    pout.write(buff,0,len);
//                }
                pout.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    pout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        },"发送线程").start();

        new Thread(()->{
            byte[] buff = new byte[1024];
            int len = -1;
            try{
                System.out.println("从管道读取数据");
                while((len = pin.read(buff))>0) {
                    System.out.println(new String(buff,0,len));
                }
                System.out.println("读取完毕");
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    pin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        },"接收线程").start();
    }
}
